//
//  SuccessScreenViewController.m
//  CS Inventory Manager
//
//  Created by Ian Smith on 3/24/13.
//  Copyright (c) 2013 Transylvania University. All rights reserved.
//

#import "SuccessScreenViewController.h"
#import "AppDelegate.h"
#import "CategoryViewController.h"

@interface SuccessScreenViewController ()

@end

@implementation SuccessScreenViewController
@synthesize selectedItem, selectedDueDate, selectedPatron, cameFromDVC, selectedFaculty, agreement, signatures;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)exitButton:(id)sender
{
    //Grab appdelegate so we can get prof ID
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    int profID = appDelegate.loggedInProfessorId;
    if (!selectedFaculty) {
        //This is if the patron is a student!
        //Upload the checkout to database here!
        //Item is selectedItem
        //selectedPatron is the array of selected patrons
        //Due Date is selectedDueDate
        //agreement is the string that represents the text of the agreement
        //signatures is the array of signature images. Index corresponds to the selectedPatron array
        
        //Need to parse the date so that it uploads in YYYY-MM-DD format without the unneeded time stamp
        NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit| NSMonthCalendarUnit| NSYearCalendarUnit fromDate:selectedDueDate];
        NSMutableString *date = [[NSMutableString alloc] init];
        [date appendFormat:@"%d",components.year];
        [date appendString:@"-"];
        if (components.month < 10) {
            [date appendString:@"0"];
        }
        [date appendFormat:@"%d", components.month];
        [date appendString:@"-"];
        if (components.day < 10) {
            [date appendString:@"0"];
        }
        [date appendFormat:@"%d", components.day];
        
        //For now, just grab the first student in the array to upload as the patron. This will change once the url is updated for the possibility of multiple patrons
        Patron *tempStudent = selectedPatron[0];
        
        NSString *urlStr = [NSString stringWithFormat:@"http://www.cs.transy.edu/zoellers/inventory/checkout.php?secret=pass&patid=%d&itemid=%d&notes=%@&retdate=%@&profid=%d", tempStudent.patronId, selectedItem.itemId, selectedItem.notes, date, profID];
        NSString *final = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"The url is: >>>>>%@<<<<<", final);

        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:final]];
        
        // make web request and catch error
        NSError * e;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];
        
        // log the value returned from the web server		
        NSString *value = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];		
        NSLog(@"return from web: %@", value);
        
        // get the auto_increment value from web (if new)
        int coID = [[[value componentsSeparatedByString:@"*"] objectAtIndex:1] integerValue];
        NSLog(@"Got back from web: %i", coID);
        
        //Print checkout to the log for debugging purposes
        NSLog(@"COMPLETED CHECKOUT FOR:");
        NSLog(@"ITEM: %@ TO PATRON: %@ DUE: %@", selectedItem.model, tempStudent.lastName, selectedDueDate);
            
        for (int i = 0; i < [selectedPatron count]; i++) {
            // create unique string for the signature
            NSString *imageUniqueName = [NSString stringWithFormat:@"%d-%d",coID,[[selectedPatron objectAtIndex:i] patronId]];
            
            NSString *urlStr = [NSString stringWithFormat:@"http://www.cs.transy.edu/zoellers/inventory/checkoutAddPatronTo.php?secret=pass&patid=%d&co=%d&img=%@", [[selectedPatron objectAtIndex:i] patronId], coID,imageUniqueName];
            NSString *final = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSLog(@"The url is: >>>>>%@<<<<<", final);
                
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:final]];
                
            // make web request and catch error
            NSError * e;
            NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];
                
            // log the value returned from the web server
            NSString *value = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"return from web: %@", value);
            //Print checkout to the log for debugging purposes
            NSLog(@"Added Patron %d to Checkout %i",[[selectedPatron objectAtIndex:i] patronId],coID);
            
            // actually upload the signature
            [self uploadImage:[signatures objectAtIndex:i] withName:imageUniqueName];

        }
        
        //This is a hard-coded way of closing out of all of the checkout wizard screens at once. There is probably
        // a better and safer way to go about this. I will look into it. - BZ moved down to consolidate
        if (cameFromDVC) {
            [self.presentingViewController.presentingViewController.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:NULL];
        } else {
            [self.presentingViewController.presentingViewController.presentingViewController.presentingViewController.presentingViewController viewWillAppear:NO];
            [self.presentingViewController.presentingViewController.presentingViewController.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:NULL];
            
        }
        
        
    } else {
        //This is if the patron is a faculty member!
        //Upload to database here!
        //Item is selectedItem
        //Patron is selectedFaculty
        //Complete the checkout process here
        NSString *urlStr = [NSString stringWithFormat:@"http://www.cs.transy.edu/zoellers/inventory/checkout.php?secret=pass&patid=%d&itemid=%d&notes=%@&retdate=%d&profid=%d", selectedFaculty.patronId, selectedItem.itemId, selectedItem.notes, 0, profID];
        NSString *final = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        NSLog(@"The url is: >>>>>%@<<<<<", final);
        
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:final]];
        
        // make web request and catch error
        NSError * e;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];
        
        // log the value returned from the web server
        NSString *value = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"return from web: %@", value);
        NSLog(@"COMPLETED CHECKOUT FOR:");
        NSLog(@"ITEM: %@ TO PATRON: %@", selectedItem.model, selectedFaculty.lastName);
        
        
        int coID = [[[value componentsSeparatedByString:@"*"] objectAtIndex:1] integerValue];
        NSLog(@"Got back from web: %i", coID);
        
        
        urlStr = [NSString stringWithFormat:@"http://www.cs.transy.edu/zoellers/inventory/checkoutAddPatronTo.php?secret=pass&patid=%d&co=%d&img=%@", [selectedFaculty patronId], coID,@""];
        final = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"The url is: >>>>>%@<<<<<", final);
            
        request = [NSURLRequest requestWithURL:[NSURL URLWithString:final]];
            
        // make web request and catch error
        data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];
            
        // log the value returned from the web server
        value = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"return from web: %@", value);
        //Print checkout to the log for debugging purposes
        NSLog(@"Added Patron %d to Checkout %i",[selectedFaculty patronId],coID);
        
        
        //This is a hard-coded way of closing out of all of the checkout wizard screens at once. There is probably
        // a better and safer way to go about this. I will look into it. - BZ moved down to consolidate
        if (cameFromDVC) {
            [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:NULL];
        } else {
            [self.presentingViewController.presentingViewController.presentingViewController viewWillAppear:NO];
            [self.presentingViewController.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:NULL];
            
        }
        
    }
}

/* credit - http://stackoverflow.com/questions/11413846/uploading-an-image-from-ios-to-php?rq=1 */

- (void) uploadImage:(UIImage *)theImage withName:(NSString *)imageName {
    
    NSData *imageData = UIImagePNGRepresentation(theImage);
    NSString *urlString = [NSString stringWithFormat:@"http://www.cs.transy.edu/zoellers/inventory/uploadImage.php"];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    
    NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    
    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"%@.png\"\r\n",imageName] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:body];
    
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    
    NSLog([NSString stringWithFormat:@"Image Return String: %@", returnString]);
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
